import React, { Component } from 'react';
import { Button, Form, Input } from 'antd';

class EditUser extends Component {
  constructor(props) {
    super(props);
    this.formRef = React.createRef();
  }

  componentDidUpdate(prevProps) {
    if (this.props.currentUser&&this.props.currentUser.userId!==prevProps.currentUser?.userId) {
      this.formRef.current.setFieldsValue(this.props.currentUser);
    }
  }

  onFinish=(values)=>{
    const {userId}=this.props.currentUser;
    const url=`http://1.94.134.166:8805/user/${userId}`;
    fetch(url,{
      method:'PUT',
      body:JSON.stringify(values),
      headers:{
        "Content-Type":'application/json',
        Authorization:localStorage.getItem('Authorization'),
      },
    })
      .then((response)=>response.json())
      .then((res)=>{
        console.log(res);
        const{code=0}=res;
        if (code==0){
          this.props.refresh();
          this.props.closeDrawer();
        }
      })
  };

  render() {
    return (
      <>
        <Form
          onFinish={this.onFinish}
          ref={this.formRef}
        >
          <Form.Item
            name="username"
            label="用户名称"
            rules={[
              { required:true,message:'请输入用户名称!'},
            ]}
          >
            <Input size="large" placeholder="请输入用户名称" />
          </Form.Item>


          <Form.Item>
            <Button type="primary" htmlType="submit">
              编辑
            </Button>
          </Form.Item>
        </Form>
      </>
    );
  }
}

export default EditUser;
